import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:magma/heartbeat/helpers/magma_tap.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:path_provider/path_provider.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../comms_link/app_state.dart';
import '../../heartbeat/blueprint/user_model.dart';

/// 用户资料修改器
class ProfileModifier extends BaseViewModel {
  final TextEditingController usernameInputController = TextEditingController();
  final TextEditingController signatureInputController =
      TextEditingController();

  String? _temporaryAvatarPath;
  String? get temporaryAvatarPath => _temporaryAvatarPath;

  ProfileModifier() {
    _loadCurrentUserData();
  }

  /// 加载当前用户数据
  void _loadCurrentUserData() {
    final user = appState.userStore.currentUser;
    if (user != null) {
      usernameInputController.text = user.username;
      signatureInputController.text = user.signature;
      notifyListeners();
    }
  }

  /// 获取当前用户
  UserModel? get currentUser => appState.userStore.currentUser;

  /// 获取显示的头像路径
  String get displayAvatarPath {
    if (_temporaryAvatarPath != null) return _temporaryAvatarPath!;
    return currentUser?.avatar ?? MagmaConstant.avatar1;
  }

  /// 选择图片
  Future<void> selectImage(BuildContext context) async {
    try {
      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
          textDelegate: const EnglishAssetPickerTextDelegate(),
        ),
      );

      if (result != null && result.isNotEmpty) {
        await _processSelectedImage(result.first);
      }
    } catch (e) {
      setError('Failed to pick image: $e');
    }
  }

  /// 处理选中的图片
  Future<void> _processSelectedImage(AssetEntity asset) async {
    try {
      setBusy(true);

      // 获取图片文件
      final File? file = await asset.file;
      if (file == null) {
        setError('Failed to get image file');
        return;
      }

      // 获取应用文档目录
      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final String targetDirPath = '${appDocDir.path}/avatars';

      // 创建目录（如果不存在）
      final Directory targetDir = Directory(targetDirPath);
      if (!await targetDir.exists()) {
        await targetDir.create(recursive: true);
      }

      // 生成新的文件名
      final String fileName =
          'avatar_${DateTime.now().millisecondsSinceEpoch}.${file.path.split('.').last}';
      final String targetPath = '$targetDirPath/$fileName';

      // 复制文件到目标位置
      await file.copy(targetPath);

      // 更新临时头像路径
      _temporaryAvatarPath = targetPath;
      notifyListeners();

      // 立即保存头像到用户信息
      await _saveAvatarToUser();
    } catch (e) {
      setError('Failed to process image: $e');
    } finally {
      setBusy(false);
    }
  }

  /// 保存头像到用户信息
  Future<void> _saveAvatarToUser() async {
    if (_temporaryAvatarPath == null) return;

    final result = await appState.userStore.updateUserInfo(
      avatar: _temporaryAvatarPath,
    );

    if (!result) {
      setError('Failed to update avatar');
    }
  }

  /// 保存用户名
  Future<void> persistUsername() async {
    final username = usernameInputController.text.trim();
    if (username.isEmpty) {
      setError('Username cannot be empty');
      return;
    }

    final result = await appState.userStore.updateUserInfo(username: username);

    if (!result) {
      setError('Failed to update username');
    }
  }

  /// 保存签名
  Future<void> persistSignature() async {
    final signature = signatureInputController.text.trim();
    if (signature.isEmpty) {
      setError('Signature cannot be empty');
      return;
    }

    final result = await appState.userStore.updateUserInfo(
      signature: signature,
    );

    if (!result) {
      setError('Failed to update signature');
    }
  }

  @override
  void dispose() {
    usernameInputController.dispose();
    signatureInputController.dispose();
    super.dispose();
  }
}

/// 编辑资料页面
class EditStory extends StatefulWidget {
  const EditStory({super.key});

  @override
  State<EditStory> createState() => _EditStoryState();
}

class _EditStoryState extends State<EditStory> {
  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<ProfileModifier>.reactive(
      viewModelBuilder: () => ProfileModifier(),
      builder: (context, viewModel, child) {
        return Scaffold(
          backgroundColor: MagmaColor.black,
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(MagmaConstant.background),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              child: Column(
                children: [
                  // 顶部栏
                  _constructAppBar(),

                  // 内容区域
                  Expanded(
                    child: SingleChildScrollView(
                      child: Padding(
                        padding: EdgeInsets.symmetric(horizontal: 20.w),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            SizedBox(height: 40.h),

                            // 头像编辑区域
                            _constructAvatarSection(viewModel),

                            SizedBox(height: 48.h),

                            // 用户名编辑区域
                            _constructInputField(
                              label: 'Name',
                              controller: viewModel.usernameInputController,
                              onChanged: (_) => viewModel.persistUsername(),
                            ),

                            SizedBox(height: 24.h),

                            // 签名编辑区域
                            _constructInputField(
                              label: 'Sign',
                              controller: viewModel.signatureInputController,
                              onChanged: (_) => viewModel.persistSignature(),
                              maxLines: 3,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  /// 构建顶部栏
  Widget _constructAppBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          // 返回按钮
          MagmaTap(
            onTap: () => QR.back(),
            child: Image.asset(
              MagmaConstant.back,
              width: 20.w,
              height: 20.w,
              color: MagmaColor.white,
            ),
          ),

          // 标题
          Expanded(
            child: Center(
              child: Text('Revise').blackHanSans(
                fontSize: 24.sp,
                color: MagmaColor.white,
                fontWeight: FontWeight.w400,
              ),
            ),
          ),

          // 占位，保持标题居中
          SizedBox(width: 20.w),
        ],
      ),
    );
  }

  /// 构建头像编辑区域
  Widget _constructAvatarSection(ProfileModifier viewModel) {
    return Stack(
      children: [
        // 头像
        MagmaTap(
          onTap: () => viewModel.selectImage(context),
          child: Container(
            width: 120.w,
            height: 120.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              image: DecorationImage(
                image: _getAvatarImageProvider(viewModel.displayAvatarPath),
                fit: BoxFit.cover,
              ),
              border: Border.all(
                color: MagmaColor.white.withOpacity(0.3),
                width: 2.w,
              ),
            ),
          ),
        ),

        // 相机图标按钮
        Positioned(
          right: 0,
          bottom: 0,
          child: MagmaTap(
            onTap: () => viewModel.selectImage(context),
            child: Container(
              width: 36.w,
              height: 36.w,
              decoration: BoxDecoration(
                color: MagmaColor.black,
                shape: BoxShape.circle,
                border: Border.all(color: MagmaColor.white, width: 2.w),
              ),
              child: Icon(
                Icons.camera_alt,
                color: MagmaColor.white,
                size: 18.w,
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 获取头像图片提供者
  ImageProvider _getAvatarImageProvider(String path) {
    // 如果路径以 '/' 开头，说明是绝对路径（本地文件）
    if (path.startsWith('/')) {
      return FileImage(File(path));
    }
    // 否则是资源路径
    return AssetImage(path);
  }

  /// 构建输入框
  Widget _constructInputField({
    required String label,
    required TextEditingController controller,
    required Function(String) onChanged,
    int maxLines = 1,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 标签
        Text(label).inter(
          fontSize: 16.sp,
          color: MagmaColor.white,
          fontWeight: FontWeight.w400,
        ),

        SizedBox(height: 12.h),

        // 输入框
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
          decoration: BoxDecoration(
            color: MagmaColor.black.withOpacity(0.3),
            borderRadius: BorderRadius.circular(12.r),
            border: Border.all(color: MagmaColor.white, width: 1.w),
          ),
          child: TextField(
            controller: controller,
            onChanged: onChanged,
            maxLines: maxLines,
            style: TextStyle(
              color: MagmaColor.white,
              fontSize: 16.sp,
              fontWeight: FontWeight.w400,
            ),
            decoration: InputDecoration(
              border: InputBorder.none,
              contentPadding: EdgeInsets.zero,
              isDense: true,
            ),
          ),
        ),
      ],
    );
  }
}
